import 'package:contained_tab_bar_view/contained_tab_bar_view.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app_01/api/dashboard.dart';
import 'package:my_app_01/components/MCard.dart';
import 'package:my_app_01/components/MEmpty.dart';
import 'package:my_app_01/components/MShimmer.dart';
import 'package:my_app_01/config.dart';
import 'package:my_app_01/utils/money.dart';
import 'package:nil/nil.dart';

import 'components/Tabs.dart';

var now = DateTime.now();
var year = now.year;
var start = DateTime(year, 1, 1);

class CockpitPage extends StatefulWidget {
  const CockpitPage({super.key});

  @override
  State<CockpitPage> createState() => _CockpitPageState();
}

class _CockpitPageState extends State<CockpitPage> with SingleTickerProviderStateMixin {
  final dataCenterList = [
    {"title": "营养改善"},
    {"title": "食安监管"},
    {"title": "学生资助"},
    {"title": "学校卫生"},
    {"title": "师生健康"},
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
            alignment: Alignment.topCenter,
            fit: BoxFit.cover,
            image: NetworkImage("https://meal.kmszzxt.cn/mp/images/bg-01.png")),
      ),
      child: Scaffold(
        body: Container(
          padding: const EdgeInsets.only(top: 40, left: 20, right: 20, bottom: 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Padding(
                padding: EdgeInsets.only(bottom: 10),
                child: Text(
                  key: ValueKey("WelcomeText"),
                  "营养改善监管",
                  style: TextStyle(color: Colors.black87, fontSize: 20, fontWeight: FontWeight.w600),
                ),
              ),
              Expanded(
                flex: 1,
                child: ContainedTabBarView(
                  tabs: dataCenterList.map((e) {
                    return Text("${e['title']}");
                  }).toList(),
                  tabBarProperties: TabBarProperties(
                    height: 32.0,
                    indicator: BoxDecoration(
                      border: Border.all(color: Colors.transparent, width: 0),
                      borderRadius: BorderRadius.circular(16),
                      image: const DecorationImage(
                        fit: BoxFit.cover,
                        image: NetworkImage("https://meal.kmszzxt.cn/mp/images/bk.jpg"),
                      ),
                    ),
                    indicatorSize: TabBarIndicatorSize.tab,
                    indicatorWeight: 2.0,
                    labelColor: Colors.white,
                  ),
                  views: [
                    ListView(
                      padding: const EdgeInsets.all(0),
                      children: [
                        HomeFundCard(),
                        HomePurchaseMCard(context: context),
                        HomeDiningMCard(context: context),
                        HomeImcomeCard(context: context),
                        HomeCostCard(context: context),
                      ],
                    ),
                    const Text('222'),
                    const Text('333'),
                    const Text('444'),
                    const Text('555'),
                  ],
                  onChange: (index) => print(index),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

/// 资金统计
class HomeFundCard extends StatelessWidget {
  HomeFundCard({
    super.key,
  });

  var fundInfo = {
    'balanceAmount': 0.00,
    'inAmount': 0.00,
    'outAmount': 0.00,
  };

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(top: 15),
      elevation: 6,
      color: Colors.white,
      surfaceTintColor: Colors.white,
      shadowColor: Colors.black38,
      clipBehavior: Clip.hardEdge,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: const BoxDecoration(
          image: DecorationImage(fit: BoxFit.cover, image: NetworkImage("https://meal.kmszzxt.cn/mp/images/bk2.jpg")),
        ),
        child: FutureBuilder(
          future: Future.wait([
            DashboardApi.getIncomeInfo({
              'statdatestart': start.toString().substring(0, 19),
              'statdateend': now.toString().substring(0, 19),
            }),
            DashboardApi.getCostInfo({
              'statdatestart': start.toString().substring(0, 19),
              'statdateend': now.toString().substring(0, 19),
            })
          ]),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const MShimmer(
                width: double.infinity,
                height: 180,
                margin: EdgeInsets.only(top: 10),
              );
            }
            if (snapshot.connectionState == ConnectionState.done) {
              var incomeData = snapshot.data?[0]['data'];
              var incomeInplan = (incomeData?['grantcentralfund'] ?? 0.00) +
                  (incomeData?['grantprovincefund'] ?? 0.00) +
                  (incomeData?['grantcityfund'] ?? 0.00) +
                  (incomeData?['grantcountyfund'] ?? 0.00);
              var incomeOutplan = (incomeData?['fisstudentmeal'] ?? 0.00) +
                  (incomeData?['fisstaffmeal'] ?? 0.00) +
                  (incomeData?['fisothermeal'] ?? 0.00) +
                  (incomeData?['fisepysalary'] ?? 0.00) +
                  (incomeData?['othersalary'] ?? 0.00);
              fundInfo['incomeInplan'] = incomeInplan;
              fundInfo['incomeOutplan'] = incomeOutplan;
              fundInfo['inAmount'] = (incomeInplan ?? 0.00) + (incomeOutplan ?? 0.00);

              var costData = snapshot.data?[1]['data'];

              var costOutPlan = (costData?['fisraw'] ?? 0.00) +
                  (costData?['fislaborcost'] ?? 0.00) +
                  (costData?['fiswecost'] ?? 0.00) +
                  (costData?['fisfuelcost'] ?? 0.00) +
                  (costData?['fisoffcost'] ?? 0.00) +
                  (costData?['fismaintcost'] ?? 0.00);
              fundInfo['inalter'] = costData?['finraw'] ?? 0.00;
              fundInfo['costOutPlan'] = costOutPlan ?? 0.00;
              fundInfo['outAmount'] = (costData?['finraw'] ?? 0.00) + (costOutPlan ?? 0.00);
              return Column(
                children: [
                  ListTile(
                    title: Text(
                      "${MoneyUtils.amountFormat(fundInfo['inAmount']! - fundInfo['outAmount']!)}元",
                      textAlign: TextAlign.center,
                      style: const TextStyle(color: Colors.white, fontSize: 24),
                    ),
                    subtitle: const Text(
                      "资金结余",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white, fontSize: 12),
                    ),
                  ),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: ListTile(
                          title: Text(
                            "${MoneyUtils.amountFormat(fundInfo['inAmount'])}元",
                            textAlign: TextAlign.center,
                            style: const TextStyle(color: Colors.white, fontSize: 18),
                          ),
                          subtitle: const Text(
                            "资金收入",
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 1,
                        height: 30,
                        child: DecoratedBox(
                          decoration: BoxDecoration(color: Colors.white60),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: ListTile(
                          title: Text(
                            "${MoneyUtils.amountFormat(fundInfo['outAmount'])}元",
                            textAlign: TextAlign.center,
                            style: const TextStyle(color: Colors.white, fontSize: 18),
                          ),
                          subtitle: const Text(
                            "资金支出",
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              );
            }
            return nil;
          },
        ),
      ),
    );
  }
}

/// 采购数据统计
class HomePurchaseMCard extends StatelessWidget {
  const HomePurchaseMCard({
    super.key,
    required this.context,
  });

  final BuildContext context;

  @override
  Widget build(BuildContext context) {
    return MCard(
        title: const Text(
          "采购数据统计",
          style: MCard.defaultTitleStyle,
        ),
        right: const Text(
          "查看详情",
          style: MCard.defaultRightTextStyle,
        ),
        icon: Icons.shopping_cart,
        rightTap: () {
          EasyLoading.showInfo("查看详情");
        },
        child: FutureBuilder(
            future: DashboardApi.getPurchaseData({
              'statdatestart': start.toString().substring(0, 19),
              'statdateend': now.toString().substring(0, 19),
            }),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const MShimmer(
                  width: double.infinity,
                  height: 240,
                  margin: EdgeInsets.only(top: 10),
                );
              }
              if (snapshot.connectionState == ConnectionState.done) {
                var orderData = snapshot.data?['data'];
                return orderData != null
                    ? Column(
                        children: [
                          Row(
                            children: [
                              Container(
                                height: 80,
                                width: 60,
                                margin: const EdgeInsets.only(right: 10, bottom: 10),
                                padding: const EdgeInsets.all(15),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: const Color.fromRGBO(248, 248, 248, 1),
                                ),
                                child: const Text(
                                  "项目",
                                  style: TextStyle(backgroundColor: Color.fromRGBO(248, 248, 248, 1)),
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  height: 80,
                                  margin: const EdgeInsets.only(bottom: 10),
                                  padding: const EdgeInsets.all(5),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8),
                                    color: const Color.fromRGBO(248, 248, 248, 1),
                                  ),
                                  child: const Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          "订单采购",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(backgroundColor: Color.fromRGBO(248, 248, 248, 1)),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          "自行采购",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(backgroundColor: Color.fromRGBO(248, 248, 248, 1)),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                          Row(
                            children: [
                              Container(
                                height: 80,
                                width: 60,
                                margin: const EdgeInsets.only(right: 10, bottom: 10),
                                padding: const EdgeInsets.all(15),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: const Color.fromRGBO(248, 248, 248, 1),
                                ),
                                child: const Text("采购数量"),
                              ),
                              Expanded(
                                child: Container(
                                  height: 80,
                                  margin: const EdgeInsets.only(bottom: 10),
                                  padding: const EdgeInsets.all(5),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8),
                                    color: const Color.fromRGBO(248, 248, 248, 1),
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Wrap(
                                          alignment: WrapAlignment.center,
                                          crossAxisAlignment: WrapCrossAlignment.center,
                                          children: [
                                            Text(
                                              MoneyUtils.amountFormat(orderData['ordproccnt']),
                                              textAlign: TextAlign.center,
                                              style: const TextStyle(color: Colors.teal, fontSize: 20),
                                            ),
                                            const Text(
                                              "(件)",
                                              textAlign: TextAlign.center,
                                              style: TextStyle(color: Colors.grey, fontSize: 12),
                                            )
                                          ],
                                        ),
                                      ),
                                      Expanded(
                                        child: Wrap(
                                          alignment: WrapAlignment.center,
                                          crossAxisAlignment: WrapCrossAlignment.center,
                                          children: [
                                            Text(
                                              MoneyUtils.amountFormat(orderData['selproccnt']),
                                              textAlign: TextAlign.center,
                                              style: const TextStyle(color: Colors.teal, fontSize: 20),
                                            ),
                                            const Text(
                                              "(件)",
                                              textAlign: TextAlign.center,
                                              style: TextStyle(color: Colors.grey, fontSize: 12),
                                            )
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                          Row(
                            children: [
                              Container(
                                height: 80,
                                width: 60,
                                margin: const EdgeInsets.only(right: 10, bottom: 10),
                                padding: const EdgeInsets.all(15),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: const Color.fromRGBO(248, 248, 248, 1),
                                ),
                                child: const Text("采购金额"),
                              ),
                              Expanded(
                                child: Container(
                                  height: 80,
                                  margin: const EdgeInsets.only(bottom: 10),
                                  padding: const EdgeInsets.all(5),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8),
                                    color: const Color.fromRGBO(248, 248, 248, 1),
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Wrap(
                                          alignment: WrapAlignment.center,
                                          crossAxisAlignment: WrapCrossAlignment.center,
                                          children: [
                                            Text(
                                              MoneyUtils.amountFormat(orderData['ordprocamt']),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: const TextStyle(color: Colors.teal, fontSize: 20),
                                            ),
                                            const Text(
                                              "(元)",
                                              textAlign: TextAlign.center,
                                              style: TextStyle(color: Colors.grey, fontSize: 12),
                                            )
                                          ],
                                        ),
                                      ),
                                      Expanded(
                                        child: Wrap(
                                          alignment: WrapAlignment.center,
                                          crossAxisAlignment: WrapCrossAlignment.center,
                                          children: [
                                            Text(
                                              MoneyUtils.amountFormat(orderData['selprocamt']),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: const TextStyle(color: Colors.teal, fontSize: 20),
                                            ),
                                            const Text(
                                              "(元)",
                                              textAlign: TextAlign.center,
                                              style: TextStyle(color: Colors.grey, fontSize: 12),
                                            )
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          )
                        ],
                      )
                    : const MEmpty(message: "暂无采购数据");
              }
              return nil;
            }));
  }
}

/// 用餐情况统计
class HomeDiningMCard extends StatelessWidget {
  const HomeDiningMCard({
    super.key,
    required this.context,
  });

  final BuildContext context;

  @override
  Widget build(BuildContext context) {
    return MCard(
      title: const Text(
        "用餐情况（人次）",
        style: MCard.defaultTitleStyle,
      ),
      right: const Text(
        "查看详情",
        style: MCard.defaultRightTextStyle,
      ),
      icon: Icons.shopping_cart,
      rightTap: () {
        EasyLoading.showSuccess("成功");
      },
      child: SizedBox(
        height: 200,
        child: FutureBuilder(
          future: DashboardApi.getMealsData({
            'statdatestart': start.toString().substring(0, 19),
            'statdateend': now.toString().substring(0, 19),
          }),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const MShimmer(
                width: double.infinity,
                height: 180,
                margin: EdgeInsets.only(top: 10),
              );
            }
            var mealInfo = snapshot.data?['data'];
            if (snapshot.connectionState == ConnectionState.done) {
              if (mealInfo == null) return const MEmpty(message: "暂无用餐情况数据");
              var mealChartSections = [
                {'name': '回族餐', "value": mealInfo?['stumealhui'] ?? 0.00},
                {'name': '正常餐', "value": mealInfo?['stumealnor'] ?? 0.00},
                {'name': '送教上门', "value": mealInfo?['stumealsend'] ?? 0.00},
                {'name': '非受助', "value": mealInfo?['stumealnot'] ?? 0.00}
              ];
              return Row(
                children: [
                  Expanded(
                    flex: 4,
                    child: BarChart(
                      BarChartData(
                        maxY: (mealInfo?['stumealnor'] ?? 0) * 1.2,
                        extraLinesData: ExtraLinesData(),
                        gridData: FlGridData(show: false),
                        borderData: FlBorderData(
                          border: const Border(
                            bottom: BorderSide(
                              color: Colors.black12,
                              width: 1,
                            ),
                          ),
                        ),
                        titlesData: FlTitlesData(
                          leftTitles: AxisTitles(drawBehindEverything: false),
                          rightTitles: AxisTitles(drawBehindEverything: false),
                          topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                          bottomTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              getTitlesWidget: (value, meta) {
                                return getTitles(value, mealChartSections);
                              },
                            ),
                          ),
                        ),
                        barGroups: mealChartSections.asMap().entries.map((e) {
                          return BarChartGroupData(
                            x: e.key,
                            barRods: [
                              BarChartRodData(
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(4),
                                  topRight: Radius.circular(4),
                                ),
                                toY: e.value['value'].toDouble(),
                                width: 24,
                                color: Colors.teal,
                              ),
                            ],
                            showingTooltipIndicators: [0],
                          );
                        }).toList(),
                        barTouchData: BarTouchData(
                          enabled: false,
                          touchTooltipData: BarTouchTooltipData(
                            tooltipBgColor: Colors.transparent,
                            tooltipPadding: EdgeInsets.zero,
                            tooltipMargin: 0,
                            getTooltipItem: (
                              BarChartGroupData group,
                              int groupIndex,
                              BarChartRodData rod,
                              int rodIndex,
                            ) {
                              return BarTooltipItem(
                                rod.toY.round().toString(),
                                const TextStyle(
                                  color: Colors.teal,
                                  fontWeight: FontWeight.bold,
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                      swapAnimationDuration: const Duration(milliseconds: 150),
                      // Optional
                      swapAnimationCurve: Curves.linear,
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    flex: 2,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              mealInfo['stumealcnt'].toString(),
                              style: const TextStyle(fontSize: 20),
                            ),
                            const Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  "学生用餐",
                                  style: TextStyle(fontSize: 12, color: Colors.grey),
                                ),
                                Text(
                                  "(人次)",
                                  style: TextStyle(fontSize: 10, color: Colors.grey),
                                ),
                              ],
                            )
                          ],
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              mealInfo['staffmealnor'].toString(),
                              style: const TextStyle(fontSize: 20),
                            ),
                            const Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  "教职工用餐",
                                  style: TextStyle(fontSize: 12, color: Colors.grey),
                                ),
                                Text(
                                  "(人次)",
                                  style: TextStyle(fontSize: 10, color: Colors.grey),
                                ),
                              ],
                            )
                          ],
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              mealInfo['staffmealtmp'].toString(),
                              style: const TextStyle(fontSize: 20),
                            ),
                            const Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  "临时人员用餐",
                                  style: TextStyle(fontSize: 12, color: Colors.grey),
                                ),
                                Text(
                                  "(人次)",
                                  style: TextStyle(fontSize: 10, color: Colors.grey),
                                ),
                              ],
                            )
                          ],
                        ),
                      ],
                    ),
                  )
                ],
              );
            }
            return nil;
          },
        ),
      ),
    );
  }
}

/// 用餐情况统计图表的动态文字组件
Widget getTitles(value, list) {
  String text = list[value.toInt()]['name'];
  return text != null
      ? Text(
          text,
          style: const TextStyle(fontSize: 10),
        )
      : nil;
}

/// 资金收入
class HomeImcomeCard extends StatelessWidget {
  const HomeImcomeCard({
    super.key,
    required this.context,
  });

  final BuildContext context;

  @override
  Widget build(BuildContext context) {
    return MCard(
      title: const Text(
        "资金收入（元）",
        style: MCard.defaultTitleStyle,
      ),
      right: const Text(
        "查看详情",
        style: MCard.defaultRightTextStyle,
      ),
      icon: Icons.shopping_cart,
      rightTap: () {
        EasyLoading.showSuccess("成功");
      },
      child: FutureBuilder(
          future: DashboardApi.getIncomeInfo({
            'statdatestart': start.toString().substring(0, 19),
            'statdateend': now.toString().substring(0, 19),
          }),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const MShimmer(
                width: double.infinity,
                height: 200,
                margin: EdgeInsets.only(top: 10),
              );
            }
            if (snapshot.connectionState == ConnectionState.done) {
              var res = snapshot.data?['data'];
              if (res == null) {
                return const MEmpty(
                  message: "暂无收入统计数据",
                  height: 200,
                );
              }
              var values = [
                {"name": '中央资金', "value": res?['grantcentralfund'] ?? 0},
                {"name": '省级资金', "value": res?['grantprovincefund'] ?? 0},
                {"name": '市级资金', "value": res?['grantcityfund'] ?? 0},
                {"name": '区县资金', "value": res?['grantcountyfund'] ?? 0},
                {"name": '学生自交', "value": res?['fisstudentmeal'] ?? 0},
                {"name": '教师自交', "value": res?['fisstaffmeal'] ?? 0},
                {"name": '代办伙食', "value": res?['fisothermeal'] ?? 0},
                {"name": '工勤人员工资', "value": res?['fisepysalary'] ?? 0},
                {"name": '其他', "value": res?['othersalary'] ?? 0},
              ];
              values.sort((a, b) => b['value'].compareTo(a['value']));
              return SizedBox(
                height: 200,
                child: Row(
                  children: [
                    Expanded(
                      flex: 4,
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: values.asMap().entries.map((entry) {
                            return Wrap(
                              crossAxisAlignment: WrapCrossAlignment.center,
                              children: [
                                Container(
                                  width: 14,
                                  height: 10,
                                  margin: const EdgeInsets.only(right: 5),
                                  decoration: BoxDecoration(
                                    color: Color(MyConfig.colors[entry.key]),
                                    borderRadius: const BorderRadius.all(Radius.circular(3)),
                                  ),
                                ),
                                Text("${entry.value['name']}: ${MoneyUtils.amountFormat(entry.value['value'])}元"),
                              ],
                            );
                          }).toList()),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Expanded(
                        flex: 3,
                        child: PieChart(
                          PieChartData(
                              centerSpaceRadius: 0,
                              borderData: FlBorderData(
                                show: false,
                              ),
                              sections: values.asMap().entries.map((entry) {
                                return PieChartSectionData(
                                  radius: 65,
                                  color: Color(MyConfig.colors[entry.key]),
                                  value: entry.value['value'],
                                  title: "",
                                  // title: "${entry.value['name']}\n${entry.value['value']}元",
                                  titleStyle: const TextStyle(color: Colors.white),
                                );
                              }).toList()),
                          swapAnimationDuration: const Duration(milliseconds: 150),
                          // Optional
                          swapAnimationCurve: Curves.linear,
                        )),
                  ],
                ),
              );
            }
            return nil;
          }),
    );
  }
}

/// 资金收入
class HomeCostCard extends StatelessWidget {
  const HomeCostCard({
    super.key,
    required this.context,
  });

  final BuildContext context;

  @override
  Widget build(BuildContext context) {
    return MCard(
      title: const Text(
        "资金支出（元）",
        style: MCard.defaultTitleStyle,
      ),
      right: const Text(
        "查看详情",
        style: MCard.defaultRightTextStyle,
      ),
      icon: Icons.shopping_cart,
      rightTap: () {
        EasyLoading.showSuccess("成功");
      },
      child: FutureBuilder(
          future: DashboardApi.getCostInfo({
            'statdatestart': start.toString().substring(0, 19),
            'statdateend': now.toString().substring(0, 19),
          }),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const MShimmer(
                width: double.infinity,
                height: 200,
                margin: EdgeInsets.only(top: 10),
              );
            }
            if (snapshot.connectionState == ConnectionState.done) {
              var res = snapshot.data?['data'];
              if (res == null) {
                return const MEmpty(
                  message: "暂无收入统计数据",
                  height: 200,
                );
              }

              var values = [
                {'name': '财政-食材费用', 'value': res?['finraw'] ?? 0.00},
                {'name': '非财政-燃料费', 'value': res?['fisfuelcost'] ?? 0.00},
                {'name': '非财政-人工费', 'value': res?['fislaborcost'] ?? 0.00},
                {'name': '非财政-维修费', 'value': res?['fismaintcost'] ?? 0.00},
                {'name': '非财政-办公费', 'value': res?['fisoffcost'] ?? 0.00},
                {'name': '非财政-食材费用', 'value': res?['fisraw'] ?? 0.00},
                {'name': '非财政-水电费', 'value': res?['fiswecost'] ?? 0.00},
              ];
              values.sort((a, b) => b['value'].compareTo(a['value']));
              return SizedBox(
                height: 200,
                child: Row(
                  children: [
                    Expanded(
                        flex: 3,
                        child: PieChart(
                          PieChartData(
                              centerSpaceRadius: 0,
                              sections: values.asMap().entries.map((entry) {
                                return PieChartSectionData(
                                  radius: 65,
                                  color: Color(MyConfig.colors[entry.key]),
                                  value: entry.value['value'],
                                  title: "",
                                  // title: "${entry.value['name']}\n${entry.value['value']}元",
                                );
                              }).toList()),
                          swapAnimationDuration: const Duration(milliseconds: 150),
                          // Optional
                          swapAnimationCurve: Curves.linear,
                        )),
                    const SizedBox(
                      width: 20,
                    ),
                    Expanded(
                      flex: 4,
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: values.asMap().entries.map((entry) {
                            return Wrap(
                              crossAxisAlignment: WrapCrossAlignment.center,
                              children: [
                                Container(
                                  width: 14,
                                  height: 10,
                                  margin: const EdgeInsets.only(right: 5),
                                  decoration: BoxDecoration(
                                    color: Color(MyConfig.colors[entry.key]),
                                    borderRadius: const BorderRadius.all(Radius.circular(3)),
                                  ),
                                ),
                                Text("${entry.value['name']}: ${MoneyUtils.amountFormat(entry.value['value'])}元"),
                              ],
                            );
                          }).toList()),
                    ),
                  ],
                ),
              );
            }
            return nil;
          }),
    );
  }
}
